package ru.hh.school;

import java.io.IOException;
import java.net.Socket;

public class User {
    private String nick;
    private Room room;
    private UserOutput output;
    private Thread outputThread;
    private Thread inputThread;
    private Socket socket;
    private boolean alive = true; // This flag protects user from double death. Only single death is allowed.

    public boolean isAlive() {
        return alive;
    }

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public Room getRoom() {
        return room;
    }

    public void setRoom(Room room) {
        this.room = room;
    }

    public User(Socket socket, ChatRouter chatRouter, Room defaultRoom) throws IOException {
        this.room = defaultRoom;
        this.socket = socket;

        output = new UserOutput(socket.getOutputStream(), this, chatRouter);
        outputThread = new Thread(output);
        outputThread.start();

        defaultRoom.addUser(this);

        UserInput input = new UserInput(socket.getInputStream(), this, chatRouter);
        inputThread = new Thread(input);
        inputThread.start();
    }

    public void sendMessage(String message) {
        output.add(message);
    }

    public void close() {
        if (this.alive) {
            inputThread.interrupt();
            outputThread.interrupt();
            room.delUser(this);
            try {
                socket.close();
            } catch (IOException e) {
                //ignore
            }
            this.room = null;
            this.nick = null;
            this.alive = false;
        }
    }

    @Override
    public String toString() {
        return "User[" +
                this.getNick() +
                " in room" + room +
                " ]";
    }
}
